<?php

use think\migration\Migrator;
use think\migration\db\Column;

class LastPrivateMessageFunction extends Migrator
{
    /**
     * Change Method.
     *
     * Write your reversible migrations using this method.
     *
     * More information on writing migrations is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
     *
     * The following commands can be used in this method and Phinx will
     * automatically reverse them when rolling back:
     *
     *    createTable
     *    renameTable
     *    addColumn
     *    renameColumn
     *    addIndex
     *    addForeignKey
     *
     * Remember to call "create()" or "update()" and NOT "save()" when working
     * with the Table class.
     */
    public function up()
    {
        $sql = <<<EOF
DROP FUNCTION IF EXISTS last_private_message_id;
set global log_bin_trust_function_creators=TRUE;
delimiter //
CREATE FUNCTION last_private_message_id(left_id INT, right_id INT) RETURNS INT
BEGIN
    DECLARE pmid INT;
    SELECT id INTO pmid
    FROM private_messages
    WHERE ((to_id = left_id AND from_id = right_id) OR (from_id = left_id AND to_id = right_id))
    ORDER BY update_at DESC LIMIT 1;
    RETURN pmid;
END;//
delimiter ;
set global log_bin_trust_function_creators=FALSE;
EOF;
        $this->execute($sql);
    }

    public function down()
    {
        $sql = <<<EOF
        DROP FUNCTION IF EXISTS last_private_message_id;
EOF;
        $this->execute($sql);
    }
}
